/**
 * @team Samurai Pizza Cats
 * 1. Tom Doron
 * 2. Gal Rotem
 * 3. Dor Porat
 */
 

import interp.Interpreter;
import ir.TacGenerator;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import lex.Lexer;
import lex.Token;
import pars.Calc;
import pars.ICGrammar;
import pars.Tree;
import scoping.Checker;
import scoping.helpers.SemanticCheckerResponse;

public class Main
{
	public static void main(String[] args)
	{
		Lexer lex = new Lexer();
		Calc calc = new Calc();
		Checker checker = new Checker();
		List<Token> tokens = new LinkedList<Token>();
		try {
			Tree libAst = null;
			if (args.length > 1 && args[1].startsWith("-L")) {
				List<Token> libTokens = new LinkedList<Token>();
				lex.process(args[1].substring(2), libTokens);
				libAst = calc.process(libTokens, ICGrammar.LibicRules);
			}
			lex.process(args[0], tokens);
			Tree ast = calc.process(tokens, ICGrammar.Rules);
			if (libAst != null){
				List<Tree> classesNodes = new ArrayList<Tree>();
				classesNodes.add(libAst);
				classesNodes.addAll(Arrays.asList(ast.subtrees));
				ast.subtrees = classesNodes.toArray(ast.subtrees);
			}
			
			SemanticCheckerResponse response = checker.check(ast,true);
			if (!response.is_isValid()){
				System.out.println(response.get_errorMessage());
				return;
			}
			TacGenerator tacGenerator = new TacGenerator(checker);
			String str = tacGenerator.invoke(ast);
			//System.out.println(str);
		}
		catch (Exception e) {
			System.out.println(e.getMessage());
			System.exit(1);
		}

	}	
}